<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>

<!DOCTYPE HTML>
<html>
<head>
    <base href="${ctx }/">
    <title>车辆信息列表</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <link rel="stylesheet" href="plugin/bootstrap-3.3.7-dist/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="css/bootstrap-datetimepicker.css"/>
    <link rel="stylesheet" href="plugin/bootstrap-table/dist/bootstrap-table.css">
    <!-- <link rel="stylesheet" href="css/zoom.css" media="all" />  -->
    <link rel="stylesheet" href="alert/alert.css">
     <style type="text/css">
        a{
        color: #73879C;
        }
        #filediv{
    border: 2px solid #ccc6c6;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
    margin-right: 20px;
  }
   #filediv1{
  border: 2px solid #ccc6c6;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
    margin-right: 20px;
  }
    .addbr{
     float: right;
    margin-right: 80px;
  }
  .pad{
    padding-left:15px;
    padding-top:10px;
  }
  .im{
     padding:10px;
  }
  .padtr{
      margin-top:5px;
  }
  #filediv{
  border: 2px solid #ccc6c6;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    display: inline-block;
    margin-right: 20px;
  }
    </style>
</head>
<body>

        <div>
            <ul class="breadcrumb">
                <li>
                    <i class="icon-home home-icon"></i>
                    <a href="javascript:void(0)">Vehicle Management(车辆管理)</a>
                </li>
                <li class="active">
                    <a href="view/car/car_list.jsp">Vehicle Type List(车辆列表)</a>
                </li>
            </ul>
        </div>
            <div class="form-inline" role="form" method="post" id="queryForm">
                <div class="form-group">
                    <label>Vehicle Registration Time(车辆注册时间):</label>
                    <input type="text" class="form-control input-append form_date" id="startTime">-
                    <input type="text" class="form-control input-append form_date" id="endTime">
                </div>
                <div class="form-group">
                    <label>Model(型号):</label>
                    <input type="text" id="models"  class="form-control">
                </div>
                <div class="form-group">
                    <label>REGO(车牌号):</label>
                   <input type="text" id="licensePlate"  class="form-control">
                </div>
                   <div class="form-group">
                    <label>Make(品牌):</label>
                     <input type="text" id="vehicleRand" class="form-control">
                </div>
                   
                <input type='hidden' id="sortName" />
                 <div class="form-group">
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <button id="queryBtn" onclick="doQuery1('demo-table',queryParams1())" class="btn btn-primary">Search
                </button>
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <button id="queryBtn" onclick="add()" class="btn btn-primary">Add Vehicle
                </button>
                </div>	
            </div>
        <br>
        <p id="onLineNum" style='text-align: center;color: red;'></p>
    <table id="demo-table"></table>
   
</body>

<!-- 加载需要的js -->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="plugin/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
<script src="js/jquery-bootstrap-pagination.js"></script>
<script src="plugin/bootstrap-table/dist/bootstrap-table.min.js"></script>
<script src="plugin/bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js"></script>
<script src='alert/alert.js'></script>
<!--时间  -->
<script src="js/bootstrap-datetimepicker.js"></script>
<script src="js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="js/common.js"></script>
<script src="plugin/layer/layer.js"></script>
<script type="text/javascript" charset="utf-8">
    var M = {}

    $('.form_date').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',
        format: 'dd/mm/yyyy',
        todayBtn: 1,
        autoclose: 1,
    });

    $(function () {
        initPath("${ctx }");
        inittable1('demo-table', queryParams, columns, "car/getCarList");
    });
   
    
function inittable1(id,queryParams,columns,url){
	$('#'+id+'').bootstrapTable({
    	method:'GET',
        dataType:'json',
        contentType: "application/x-www-form-urlencoded",
        cache: false,
        striped: true,    
        sortOrder:"desc",
        //是否显示行间隔色
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        url:url,
        height: $(window).height() - 110,
        width:$(window).width(),
        /* showColumns:true, */
        pagination:true,
        queryParams : queryParams,
        minimumCountColumns:2, 
        pageNumber:1,                       //初始化加载第一页，默认第一页
              pageSize:10,                       //每页的记录行数（*）
              pageList: [5,10,15,25,50,100],        //可供选择的每页的行数（*）
              uniqueId: "id",                     //每一行的唯一标识，一般为主键列
        showExport: true,                    
        exportDataType: 'all',
        responseHandler: responseHandler,
        columns: columns,
        onSort:function(name, order){
        	$('#sortName').val(name);
        }
    });
}

    var columns = [{field: '', title: 'Choose', checkbox: true},
        {
            field: 'picture',
            title: 'Photo(图片)',
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
                return value == null ? "" : "<img src='" + value + "' style='width:60px;height:60px'/>";
            }
        },
        {
            field: 'licensePlate',
            title: 'REGO(车牌)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'vehicleRand',
            title: 'Make(品牌)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'models',
            title: 'Model(模型)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'color',
            title: 'Color(颜色)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'productionDate',
            title: 'Compliance Date(生产时间)',
            align: 'center',
            formatter: timeDateString,
            valign: 'middle'
            
        },
        {
            field: 'seatNum',
            title: 'Seating Capacity(座位)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'serverType',
            title: 'Service category(服务类型)',
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
            	var str="";
            	if(value==1){
            		str="fab ONE";
            	}else if(value==2){
            		str="fab";
            	}else{
            		str="fab PRO";
            	}
                return str;
            }
        },
        {
            field: 'mileage',
            title: 'Kilometer(公里)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'driverName',
            title: 'Driver Name(司机名称)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'driverPhone',
            title: 'Driver Phone(司机电话)',
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'registTime',
            title: 'Registration Time(注册时间)',
            align: 'center',
            valign: 'middle',
            formatter: timeDateString,
            sortable:true
        },
        {
            field: 'hireCarLicense',
            title: 'Hire Car License(汽车执照)',
            align: 'center',
            valign: 'middle',
            sortable:true
        },
        {
            field: 'registTime',
            title: 'Vehicle Inspection(车辆检验)',
            align: 'center',
            valign: 'middle',
            sortable:true
        },
        {
            field: 'insurance',
            title: 'Insurance(保险)',
            align: 'center',
            valign: 'middle',
            sortable:true
        },
        {
            field: 'id',
            title: 'Operation(操作)',
            align: 'center',
            valign: 'middle',
            formatter: function (value, row, index) {
            	sessionStorage.setItem("car"+value, JSON.stringify(row)); 
                var str = '<a style="margin-left:5px;color:#03A9F4" style="margin-left:5px" href="javascript:void(0)" onclick="add('+value+')">Detail</a>'
                    +'<a style="margin-left:5px;color:#03A9F4" style="margin-left:5px" href="javascript:void(0)" onclick="del('+value+')">Delete</a>'
                    +'<a style="margin-left:5px;color:#03A9F4" style="margin-left:5px" href="javascript:void(0)" onclick="add('+value+',1)">Edit</a>';
                return str;
            }
        }
    ];
    //删除车辆
    function del(value){
    	 $.ajax({
             type: "get",
             url: "car/deleteCar?carId="+value,
             success: function(data){    	            	 
            if(data.code==200){
            	 window.location.reload();    
      	       }else{
      	    	    layer.msg(data.msg);
      	       }
                      }
         }); 
    	
    }
    //type 1查看详情 2添加
function add(id,type){
	var row=JSON.parse(sessionStorage.getItem("car"+id));
	var title="Vehicle Details";var licensePlate="";var seatNum="";
	var serverType="";var vehicleRand="";
	var productionDate="";var color="";
	var mileage="";var uId="";var picture="";var models="";var noCriminal="";var isdisabled="";
	var but="";
	isdisabled="disabled";
		if(type!=undefined){
			but="<tr align=\"center\" class=\"padtr\"><td colspan=\"5\" ><button type=\"button\" onclick=\"save()\" style='margin-top: 10px;' class=\"btn btn-info btn1\">&nbsp;Save&nbsp;&nbsp;</button>"
				+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
				+"<button type=\"button\" style='margin-top: 10px;' onclick=\"cacel()\" class=\"btn btn-info btn1\">&nbsp;&nbsp;Cancel&nbsp;&nbsp;</button></td></tr>";
			isdisabled="";
		}
	if(id==undefined){
		isdisabled="";
		but="<tr align=\"center\" class=\"padtr\"><td colspan=\"5\" ><button type=\"button\" onclick=\"save()\" style='margin-top: 10px;' class=\"btn btn-info btn1\">&nbsp;Save&nbsp;&nbsp;</button>"
			+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
			+"<button type=\"button\" style='margin-top: 10px;' onclick=\"cacel()\" class=\"btn btn-info btn1\">&nbsp;&nbsp;Cancel&nbsp;&nbsp;</button></td></tr>";
		
	}	
	if(row!=null){
		serverType= row.serverType==null?"":row.serverType;
		vehicleRand=row.vehicleRand==null?"":row.vehicleRand;
		licensePlate=row.licensePlate==null?"":row.licensePlate;
		uId=row.uId==null?"":row.uId;
		models=row.models==null?"":row.models;
		picture=row.picture==null?"":row.picture;
		noCriminal=row.noCriminal==null?"":row.noCriminal;
		productionDate = timeDateString(row.productionDate);
		color=row.color==null?"":row.color;
		seatNum=row.seatNum==null?"":row.seatNum;
		mileage=row.mileage==null?"":row.mileage;
	}
	var str="<form class=\"form-horizontal\" id='forms'>"
	      +"<table>"
		  +"  <tr class=\"padtr\"><td class=\"pad\">REGO(车牌):</td> "
		  +" <td ><input type=\"text\" id=\"licensePlate1\" name=\"licensePlate\" class=\"form-control\" "+isdisabled+" value='"+licensePlate+"'><input type=\"hidden\" id=\"id\" name='id'  value='"+id+"' disabled></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Service category(服务类型):</td> "
		  +" <td ><select id='serverType' class=\"form-control\" name=\"serverType\"><option value='1'>fab ONE</option><option value='2'>fab</option><option value='3'>fab PRO</option><option value='4'>Concierge</option></select></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Make(品牌):</td> "
		  +" <td ><input type=\"text\" id=\"vehicleRand\" name=\"vehicleRand\" class=\"form-control\" value='"+vehicleRand+"' "+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Compliance Date(生产日期):</td> "
		  +" <td ><input type=\"text\" id=\"productionDate\" name=\"productionDate\" class=\"form-control input-append form_date\" value='"+productionDate+"' "+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Color(颜色):</td> "
		  +" <td ><input type=\"text\" id=\"color\" class=\"form-control name='color' \" value='"+color+"'"+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Kilometer(公里):</td> "
		  +" <td ><input type=\"number\" id=\"mileage\" class=\"form-control \" oninput='reg(\"mileage\")' name=\"mileage\" value='"+mileage+"' "+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Model:</td> "
		  +" <td > <input type=\"text\" id=\"models\"  class=\"form-control\" name='models' value='"+models+"'"+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Seating Capacity(座位):</td> "
		  +" <td > <input type=\"text\" id=\"seatNum\"  class=\"form-control\" name='seatNum' oninput='reg(\"seatNum\")' value='"+seatNum+"'"+isdisabled+"></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Vehicle Body(车型):</td> "
		  +" <td > <select name='carType' class=\"form-control\"><option>SUV</option><option>SEDAN</option><option>COUPE</option><option>PICKUP</option><option>HATCH BACK</option></select></td></tr> "
		  +"  <tr class=\"padtr\"><td class=\"pad\">Driver (司机):</td> "
		  +" <td ><select id='uId'  class=\"form-control\" name=\"uId\"></select></td></tr> "
	    +" <tr class=\"padtr\"><td class=\"pad\">Photo(图片):</td> "+
        "<td style=\"padding: 10px 20px;\"><div id=\"filedivs\" ><label for=\"file\" ><div id=\"filediv\" ><span class=\"glyphicon glyphicon-plus im\"></span></div>"+
        "<input type=\"file\" id=\"file\"  onchange=\"fileSize(this,'')\" accept=\"image/jpeg,image/jpg,image/png\" style=\"display:none\"/>  </label></div>"+
        "<input type=\"hidden\" id=\"result\" /><img src=\""+picture+"\" style=\"width:50px;height:50px;display:none\" onclick=\"javascript:$(\'#file\').click()\" id=\"imgs\"/>"
        +"</td></tr>"+
        '  <tr class="padtr"><td class="pad">Hire Car License(汽车执照):</td> '+
        '<td><input type="file" id="file2" onchange="fileSize1(this,2)"/><input type="hidden" id="result2" name="hireCarLicense"/></td></tr>'
        + '  <tr class="padtr"><td class="pad">Insurance(保险):</td> '+
        '<td><input type="file" id="file3" onchange="fileSize1(this,3)"/><input type="hidden" id="result3" name="vehicleInspection"/></td></tr>'
        + '  <tr class="padtr"><td class="pad">Vehicle Inspection(车辆检验):</td> '+
        '<td><input type="file" id="file4" onchange="fileSize1(this,4)"/><input type="hidden" id="result4" name="insurance"/></td></tr>'
        +but +'</table></form>';
		layer.open({
			  type: 1,
			  title: title,
			  skin: 'layui-layer-rim', //加上边框
			  area: ['620px', '660px'], //宽高
			  content:str
			  });
		 $('.form_date').datetimepicker({
		        minView: "month", //选择日期后，不会再跳转去选择时分秒
		        language: 'zh-CN',
		        format: 'dd/mm/yyyy',
		        todayBtn: 1,
		        autoclose: 1,
		    });
		initUId(uId);
		if(row!=null){
			if(picture!=""){
				 $('#filedivs').css("display","none");
			      $('#imgs').css("display","block");
			      $('#imgs').attr("src",picture);
			}
			if(noCriminal!=""){
				 $('#filedivs1').css("display","none");
			      $('#imgs1').css("display","block");
			      $('#imgs1').attr("src",picture);
			}
			$('#serverType').val(serverType);
			$('#vehicleRand').val(vehicleRand);
			$('#licensePlate1').val(licensePlate);
			if(productionDate!=null&&productionDate!=""){
				var pd=productionDate.split('-');
				$('#productionDate').val(pd[2]+"/"+pd[1]+"/"+pd[0]);
			}
			
		}
}
    
//点击div时点击file
function fileSize1(obj,num){
      console.log(obj.files[0])
	var formdata = new FormData();
    formdata.append("file", obj.files[0]);
    var xhr = new XMLHttpRequest();
    var index ;
    xhr.upload.addEventListener("progress", function(e) {
    	index=layer.load(1, {
    		  shade: [0.1,'#fff'] //0.1透明度的白色背景
    		});
      //console.log('e.loaded=' + e.loaded + 'e.total=' + e.total);
      console.log(e)
    }, false);
    // 完成
    xhr.addEventListener("load", function(e) {
      console.log(xhr.responseText) //返回信息
      layer.close(index);
      if(xhr.responseText!=""){
  		var response=JSON.parse(xhr.responseText);
  	    $('#result'+num+'').val(response.data);
  	}
    }, false);
    // 错误
    xhr.addEventListener("error", function(e) {
    	layer.close(index);
      // self.onFailure(file, xhr.responseText);
    }, false);

    xhr.open("POST", 'http://54.66.146.242:8080/fab_api/pcphoto/pcphotoImg', true);
    xhr.setRequestHeader("X_FILENAME", 'src');
    xhr.send(formdata);
}

    
function reg(id){
	var text=$('#'+id+'').val();
	 if(parseInt(text)<=0){
		 $('#'+id+'').css("border-color","#FF0000");
		 $('#'+id+'').val('');
		 }else{
			$('#'+id+'').css("border-color","#ccc")
		 }
}

    //保存
    function save(){
    	var data=serialize('forms');
    	data.color=$('#color').val();
    	if(data.licensePlate==""){
			 layer.msg("REGO cannot be empty");
			 return;
		}      
		if(data.serverType==""){
			 layer.msg("Service category cannot be empty");
			 return;
		}if(data.vehicleRand==""){
			 layer.msg("Make cannot be empty");
			 return;
		}if(data.productionDate==""){
			 layer.msg("Compliance Date cannot be empty");
			 return;
		}else{
			var productionDate= data.productionDate; 
			var pd=productionDate.split('/');
			productionDate=pd[2]+"-"+pd[1]+"-"+pd[0];
			data.productionDate=productionDate;
		}if(data.color==""){
			 layer.msg("Color cannot be empty");
			 return;
		}if(data.uId==""){
			 layer.msg("Driver cannot be empty");
			 return;
		}if(data.mileage==""){
			 layer.msg("Mileage cannot be empty");
			 return;
		}
		var mImg=$('#result').val();
	       data.picture=mImg;
		if(data.id==""){
			if(data.vehicleRand==""){
				 layer.msg("Make cannot be empty");
				 return;
			}
		 	  if(data.hireCarLicense==""){
				 layer.msg("Hire Car License cannot be empty");
				 return;
			}
			if(data.vehicleInspection==""){
				 layer.msg("Vehicle Inspection. cannot be empty");
				 return;
			}
			if(data.insurance==""){
				 layer.msg("Insurance cannot be empty");
				 return;
			}  
		       if(data.picture==""){
		    	   layer.msg("Vehicle pictures cannot be empty.");
					 return;
		       }
		}else{
			if(data.vehicleRand==""){
				data.vehicleRand=null;
			}
			if(data.hireCarLicense==""){
				data.hireCarLicense=null;
			}
			if(data.vehicleInspection==""){
				data.vehicleInspection=null;
			}
			if(data.insurance==""){
				data.insurance=null;
			}
			if(data.picture==""){
				data.picture=null;
			}
		}
    	 $.ajax({
             type: "post",
             url: "car/addOrUpdate",
             data: JSON.stringify(data),
             contentType:"application/json;charset=UTF-8", 
             dataType:"json",
             success: function(data){    	            	 
            if(data.code==200){
            	 window.location.reload();    
      	       }else{
      	    	    layer.msg(data.msg);
      	       }
                      }
         }); 
    }
	function cacel(){
		layer.closeAll();
	}
    //初始化司机
    function initUId(uId){
    	$.ajax({
    		  type: "get",
	            url: "user/drivers?pageSize=10000",
	            async:false,
	            success: function(data){    
	           	  console.log(data)
	          	  if(data.data.length>0){	 
	          		  var str="";
	          		  for(var i in data.data){
	          			str+="<option value='"+data.data[i].id+"'>"+data.data[i].firstName+"</option>";
	          		  }
	          		 $('#uId').html(str);
	          		 $('#uId').val(uId);
		        	 }
	       }
	        }); 
    }
//点击div时点击file
function fileSize(file,num){
	 var image = new Image();
	 var _URL = window.URL || window.webkitURL;
	 var width =0; var height = 0;
      image.onload =function(){  
         width = image.width;  
         height = image.height;
         $('#filedivs'+num+'').css("display","none");
	      $('#imgs'+num+'').css("display","block");
	      $('#imgs'+num+'').attr("src",image.src);
      }  
    	  image.src =  _URL.createObjectURL(file.files[0]);
		    var reader = new FileReader();  
		    //将文件以Data URL形式读入页面  
		    reader.readAsDataURL(file.files[0]);  
		    reader.onload=function(e){  
		    	var r = "result"+num+"";
		        var result=document.getElementById(r);  
		        //显示文件  
		        result.value=this.result;  
      }
}
    function queryParams(params) {
        var param = {
       		startTime: $('#startTime').val(),      
       		endTime: $('#endTime').val(),
       		models: $('#models').val(),
       		licensePlate: $('#licensePlate').val(),
       		vehicleRand: $('#vehicleRand').val(),
            order:this.sortOrder,
            pageNo: this.pageNumber,
            pageSize: this.pageSize
        }
        return param;
    }

    function queryParams1() {
        var param = {
       		startTime: $('#startTime').val(),      
       		endTime: $('#endTime').val(),
       		models: $('#models').val(),
       		licensePlate: $('#licensePlate').val(),
       		vehicleRand: $('#vehicleRand').val(),
            order:this.sortOrder,
            pageNo: 1,
            pageSize: this.pageSize
        }
        return param;
    }

  
</script>
</html>


